<template>
    <div>
        <el-card class="box-card">
            <h2>待分配合同列表</h2>
            <el-table :data="contracts" style="width: 100%" v-loading="loading">
                <el-table-column prop="name" label="合同名称" width="200"></el-table-column>
                <el-table-column prop="startTime" label="起草时间" width="200"></el-table-column>
                <el-table-column label="操作" width="100">
                    <template #default="scope">
                        <el-button @click="assignContract(scope.row)" type="primary" size="small">分配</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
</template>

<script>
export default {
    data() {
        return {
            contracts: [],
            loading: false // 添加加载状态
        };
    },
    created() {
        this.fetchContracts();
    },
    methods: {
        fetchContracts() {
            this.loading = true; // 开始加载
            this.axios.get('/api/contract/drafting')
                .then(response => {
                    console.log('API Response:', response.data); // Log the API response
                    if (Array.isArray(response.data.data)) {
                        // 确保数据是一个数组
                        this.contracts = response.data.data.map(contract => ({
                            name: contract.name,
                            startTime: contract.beginTime // 假设API返回的数据中包含合同的开始时间
                        }));
                    } else {
                        console.error('Error: Contracts data is not an array');
                        this.$message.error('合同数据格式错误');
                    }
                })
                .catch(error => {
                    console.error('Error fetching contracts:', error);
                    this.$message.error('获取合同列表失败');
                })
                .finally(() => {
                    this.loading = false; // 结束加载
                });
        },
        assignContract(contract) {
            // 检查合同名称是否存在于当前合同列表中
            const matchedContract = this.contracts.find(c => c.name === contract.name);
            if (matchedContract) {
                this.$router.push(`/pendingContract/${contract.name}`);
            } else {
                this.$message.error('合同名称不匹配，请重新选择');
            }
        }
    }
};
</script>

<style scoped>
.box-card {
    margin: auto;
    width: 80%;
}
.el-table th, .el-table td {
    text-align: center; /* 表格内容居中对齐 */
}
</style>
